﻿using System.Collections.Generic;
using Microsoft.Scripting.Hosting;

namespace SPCoder.Context
{
    /// <summary>
    /// 
    /// </summary>
    /// <author>Damjan Tomic</author>
    public class Context
    {
        private ContextItemNameGenerator nameGenerator;// = new ContextItemNameGenerator();
        private IDictionary<string, ContextItem> context;// = new Dictionary<string, ContextItem>();

        public IDictionary<string, ContextItem> GetContext 
        {
            get { return context; }
        }
        public void AddItem(ContextItem item)
        {
            if (item.Name == null)
                item.Name = GenerateObjectName(item);
            context.Add(item.Name, item);
            Scope.SetVariable(item.Name, item.Data);
        }
        
        public string GenerateObjectName(ContextItem item)
        {
            return nameGenerator.GenerateName(item);
        }

        public void RemoveItem(ContextItem item)
        {
            context.Remove(item.Name);
            if (Scope.ContainsVariable(item.Name))
            {
                Scope.RemoveVariable(item.Name);
            }
        }

        public ScriptScope Scope { get; set; }

        public Context()
        {
            context = new Dictionary<string, ContextItem>();
            nameGenerator = new ContextItemNameGenerator(this);
        }

        /// <summary>
        /// Renames the item in the context.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="newName"></param>
        public void RenameItem(ContextItem item, string newName)
        {
            context.Remove(item.Name);
            if (Scope.ContainsVariable(item.Name))
            {
                Scope.RemoveVariable(item.Name);
            }
            item.Name = newName;
            context.Add(item.Name, item);
            Scope.SetVariable(item.Name, item.Data);
        }
    }
}